<%--
  Created by IntelliJ IDEA.
  User: teacher
  Date: 2023/7/5
  Time: 16:46
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户注册</title>
    <script>
        let xhr;
        function checkUsername() {
            xhr = new XMLHttpRequest();
            xhr.onreadystatechange = callback;
            let username = document.getElementById("username").value;
            // xhr.open("get","${pageContext.request.contextPath}/checkUsername?username="+username);
            // xhr.send(null);


            xhr.open("post","${pageContext.request.contextPath}/checkUsername");
            // 当使用post请求时,请求头中数据格式默认使用的是text/plain
            // 而对于post请求数据传递的时候,我们需要的是application/x-www-form-urlencoded
            // 因此,需要手动指定数据传输方式
            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            // 当需要传递参数时,send方法的参数即为请求中?后面的内容
            xhr.send("username="+username);
        }

        function callback() {
            if(xhr.readyState == 4 && xhr.status == 200){
                let result = xhr.responseText;
                document.getElementById("s1").innerHTML = result;
            }
        }
    </script>
</head>
<body>
<h1>用户注册</h1>
<hr>
<form action="${pageContext.request.contextPath}/sayHello" method="post" enctype="application/x-www-form-urlencoded">
    用户名:<input type="text" id="username" name="username" onblur="checkUsername()"><span id="s1"></span><br>
    密&nbsp;&nbsp;&nbsp;码:<input type="password" name="password"><br>
    电&nbsp;&nbsp;&nbsp;话:<input type="text" name="phone"><br>
    地&nbsp;&nbsp;&nbsp;址:<input type="text" name="address"><br>
    <input type="submit" value="注册">
    <span style="color:red;">${registerMsg}</span>
</form>
</body>
</html>
